package vn.pyco.prez.tapestry.components;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;

import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.StreamResponse;
import org.apache.tapestry5.annotations.AfterRender;
import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;
import org.slf4j.Logger;

import vn.pyco.prez.io.PNGInline;
import vn.pyco.prez.model.Slide;

@Import(library="${prez.scripts}/bootstrap/bootstrap-carousel.js")
public class Carousel {
	@Inject
	private Logger _logger;
	
	@Inject
	private JavaScriptSupport _jsSupport;
	
	@Parameter
	@Property(write=false)
	private List<Slide> _source;

	@Persist
	private List<Slide> _slides;
	
	@Inject
    private ComponentResources _resources; 
	
	@Property
	private Slide _currentSlide;
	
	@Property
	private int _slideIndex;
	
	@SetupRender
	public void setupRender(){
		_slides = _source;
	}
	
	@AfterRender
	public void afterRender(){
		_jsSupport.addScript("$('.carousel').carousel({interval:null});");
		_jsSupport.addScript("$('.carousel').carousel('next');");
	}
	
	public boolean isLabelOrCaption(){
		return (_currentSlide.getLabel().trim().length() > 0 || _currentSlide.getCaption().trim().length() > 0);
	}
	
	public String getImageUrl(){
		return _resources.createEventLink("image", _slideIndex).toURI().toString();
	}
	
	@OnEvent("image")
	public StreamResponse getImage(int index){
		File image = _slides.get(index).getImage();
		InputStream is = null;
		try {
			is = new FileInputStream(image);
		} catch (FileNotFoundException e) {
			_logger.error(e.getMessage(),e);
		}
		return new PNGInline(is,"");
	}

}
